/**
 * 状态同步诊断和修复工具
 * 用于检查和修复手机端本地存储与服务端状态的不一致问题
 */

import { useDeviceStore } from '../stores/deviceStore'
import { useSocketStore } from '../stores/socketStore'
import { useVoiceStore } from '../stores/voiceStore'

// 类型定义
interface StorageInfo {
  [key: string]: any | { error: string; rawData: string | null }
}

interface StateIssue {
  type: string
  description: string
  localStored?: any
  currentState?: any
  severity: 'high' | 'medium' | 'low'
  invalidKeys?: string[]
}

interface DiagnosisReport {
  timestamp: string
  totalIssues: number
  issues: StateIssue[]
  currentStates: {
    device: {
      deviceId: string | null
      isRegistered: boolean
      pairedDevicesCount: number
      pairingStatus: 'pairing' | 'paired' | 'unpaired'
    }
    socket: {
      isConnected: boolean
      connectionStatus: string
    }
  }
  localStorage: StorageInfo
}

interface FixResult {
  fixes: string[]
  finalReport: DiagnosisReport
}

/**
 * 获取本地存储的详细信息
 */
export function getLocalStorageInfo(): StorageInfo {
  const storageKeys = [
    'smartinput-device',
    'smartinput-voice', 
    'smartinput-socket',
    'smartinput_device_info'
  ]
  
  const storageInfo: StorageInfo = {}
  
  storageKeys.forEach(key => {
    try {
      const data = localStorage.getItem(key)
      if (data) {
        storageInfo[key] = JSON.parse(data)
      } else {
        storageInfo[key] = null
      }
    } catch (error) {
      storageInfo[key] = { 
        error: (error as Error).message, 
        rawData: localStorage.getItem(key) 
      }
    }
  })
  
  return storageInfo
}

/**
 * 检查状态一致性问题
 */
export function diagnoseMismatchedStates(): DiagnosisReport {
  console.log('🔍 开始状态一致性诊断...\n')
  
  // 获取当前Zustand状态
  const deviceState = useDeviceStore.getState()
  const socketState = useSocketStore.getState()
  const voiceState = useVoiceStore.getState()
  
  // 获取本地存储状态
  const localStorageData = getLocalStorageInfo()
  
  const issues: StateIssue[] = []
  
  // 检查设备注册状态不一致
  const storedDeviceData = localStorageData['smartinput-device']
  if (storedDeviceData?.state) {
    if (storedDeviceData.state.isRegistered !== deviceState.isRegistered) {
      issues.push({
        type: 'registration_mismatch',
        description: '设备注册状态不一致',
        localStored: storedDeviceData.state.isRegistered,
        currentState: deviceState.isRegistered,
        severity: 'high'
      })
    }
    
    if (storedDeviceData.state.deviceId !== deviceState.deviceId) {
      issues.push({
        type: 'device_id_mismatch',
        description: '设备ID不一致',
        localStored: storedDeviceData.state.deviceId,
        currentState: deviceState.deviceId,
        severity: 'high'
      })
    }
    
    if (JSON.stringify(storedDeviceData.state.pairedDevices) !== JSON.stringify(deviceState.pairedDevices)) {
      issues.push({
        type: 'paired_devices_mismatch',
        description: '配对设备列表不一致',
        localStored: storedDeviceData.state.pairedDevices?.length || 0,
        currentState: deviceState.pairedDevices?.length || 0,
        severity: 'medium'
      })
    }
  }
  
  // 检查连接状态与持久化状态的冲突
  if (deviceState.isRegistered && !socketState.isConnected) {
    issues.push({
      type: 'connection_registration_conflict',
      description: '显示已注册但Socket未连接',
      severity: 'high'
    })
  }
  
  // 检查配对状态的逻辑性
  if (deviceState.pairedDevices.length > 0 && !deviceState.currentSession) {
    issues.push({
      type: 'paired_without_session',
      description: '有配对设备但没有活动会话',
      severity: 'medium'
    })
  }
  
  if (deviceState.currentSession && deviceState.pairedDevices.length === 0) {
    issues.push({
      type: 'session_without_paired',
      description: '有活动会话但没有配对设备',
      severity: 'medium'
    })
  }
  
  // 检查localStorage中是否存在不应该持久化的状态
  if (storedDeviceData?.state) {
    const invalidPersistedKeys = ['isRegistered', 'isPairing', 'pairingError', 'registrationError']
    const foundInvalidKeys = invalidPersistedKeys.filter(key => key in storedDeviceData.state)
    
    if (foundInvalidKeys.length > 0) {
      issues.push({
        type: 'invalid_persisted_states',
        description: `localStorage中包含不应该持久化的状态: ${foundInvalidKeys.join(', ')}`,
        invalidKeys: foundInvalidKeys,
        severity: 'medium'
      })
    }
  }
  
  const report: DiagnosisReport = {
    timestamp: new Date().toISOString(),
    totalIssues: issues.length,
    issues,
    currentStates: {
      device: {
        deviceId: deviceState.deviceId,
        isRegistered: deviceState.isRegistered,
        pairedDevicesCount: deviceState.pairedDevices?.length || 0,
        pairingStatus: deviceState.getPairingStatus()
      },
      socket: {
        isConnected: socketState.isConnected,
        connectionStatus: socketState.getConnectionStatus()
      }
    },
    localStorage: localStorageData
  }
  
  console.log('📊 状态诊断报告:', report)
  return report
}

/**
 * 自动修复状态不一致问题
 */
export async function autoFixStateMismatches(): Promise<FixResult> {
  console.log('🔧 开始自动修复状态不一致问题...\n')
  
  const report = diagnoseMismatchedStates()
  const fixes: string[] = []
  
  try {
    // 修复设备注册状态
    const deviceStore = useDeviceStore.getState()
    const socketStore = useSocketStore.getState()
    
    // 如果Socket已连接但设备未注册，强制注册
    if (socketStore.isConnected && socketStore.socket && !deviceStore.isRegistered) {
      console.log('🔄 修复：Socket已连接但设备未注册，开始注册...')
      try {
        await deviceStore.registerDevice(socketStore.socket)
        fixes.push('强制注册设备成功')
      } catch (error) {
        fixes.push(`强制注册设备失败: ${(error as Error).message}`)
      }
    }
    
    // 清理无效的配对状态
    if (deviceStore.pairedDevices.length > 0 && !socketStore.isConnected) {
      console.log('🔄 修复：清理离线状态下的配对设备...')
      useDeviceStore.setState({ pairedDevices: [], currentSession: null })
      fixes.push('清理离线配对设备')
    }
    
    // 修复配对状态逻辑不一致
    if (deviceStore.pairedDevices.length > 0 && !deviceStore.currentSession) {
      console.log('🔄 修复：配对设备存在但缺少会话，清理配对状态...')
      useDeviceStore.setState({ pairedDevices: [] })
      fixes.push('清理无会话的配对设备')
    }
    
    if (deviceStore.currentSession && deviceStore.pairedDevices.length === 0) {
      console.log('🔄 修复：有会话但没有配对设备，清理会话...')
      useDeviceStore.setState({ currentSession: null })
      fixes.push('清理无配对设备的会话')
    }
    
    // 清理localStorage中的无效持久化状态
    const cleaned = cleanupLegacyStorageStates()
    if (cleaned) {
      fixes.push('清理无效的持久化状态')
    }
    
    // 同步本地存储与当前状态
    console.log('🔄 修复：同步本地存储状态...')
    const currentDeviceState = useDeviceStore.getState()
    const storageKey = 'smartinput-device'
    const existingData = localStorage.getItem(storageKey)
    
    if (existingData) {
      try {
        const parsed = JSON.parse(existingData)
        parsed.state = {
          ...parsed.state,
          isRegistered: currentDeviceState.isRegistered,
          deviceId: currentDeviceState.deviceId,
          pairedDevices: currentDeviceState.pairedDevices,
          currentSession: currentDeviceState.currentSession
        }
        localStorage.setItem(storageKey, JSON.stringify(parsed))
        fixes.push('同步本地存储状态成功')
      } catch (error) {
        fixes.push(`同步本地存储失败: ${(error as Error).message}`)
      }
    }
    
  } catch (error) {
    fixes.push(`自动修复失败: ${(error as Error).message}`)
  }
  
  console.log('✅ 自动修复完成，修复项目:', fixes)
  return { fixes, finalReport: diagnoseMismatchedStates() }
}

/**
 * 清理并重置所有状态
 */
export function resetAllStates(): void {
  console.log('🗑️ 重置所有状态...')
  
  // 清理localStorage
  const keysToClean = [
    'smartinput-device',
    'smartinput-voice',
    'smartinput-socket',
    'smartinput_device_info'
  ]
  
  keysToClean.forEach(key => {
    localStorage.removeItem(key)
  })
  
  // 重置Zustand状态
  useDeviceStore.getState().resetDevice()
  useVoiceStore.getState().reset()
  
  console.log('✅ 状态重置完成，页面将刷新...')
  setTimeout(() => {
    window.location.reload()
  }, 1000)
}

/**
 * 定期状态健康检查
 */
export function startStateHealthMonitor(): () => void {
  const checkInterval = 30000 // 30秒检查一次
  
  const healthCheck = () => {
    const report = diagnoseMismatchedStates()
    
    if (report.totalIssues > 0) {
      console.warn('⚠️ 检测到状态不一致问题:', report.totalIssues, '个')
      
      // 对于高严重性问题，自动尝试修复
      const highSeverityIssues = report.issues.filter(issue => issue.severity === 'high')
      if (highSeverityIssues.length > 0) {
        console.log('🔧 检测到高严重性问题，开始自动修复...')
        autoFixStateMismatches()
      }
    }
  }
  
  // 立即执行一次检查
  healthCheck()
  
  // 启动定期检查
  const intervalId = setInterval(healthCheck, checkInterval)
  
  console.log('👀 状态健康监控已启动，每30秒检查一次')
  
  return () => {
    clearInterval(intervalId)
    console.log('👀 状态健康监控已停止')
  }
}

/**
 * 清理旧版本留下的不正确的持久化状态
 */
export function cleanupLegacyStorageStates(): boolean {
  console.log('🧹 清理旧版本的存储状态...')
  
  const deviceStorageKey = 'smartinput-device'
  const existingData = localStorage.getItem(deviceStorageKey)
  
  if (existingData) {
    try {
      const parsed = JSON.parse(existingData)
      
      // 检查是否包含不应该持久化的状态
      if (parsed.state && (
        'isRegistered' in parsed.state ||
        'isPairing' in parsed.state ||
        'pairingError' in parsed.state ||
        'registrationError' in parsed.state
      )) {
        console.log('📝 发现旧版本的持久化状态，正在清理...')
        
        // 只保留应该持久化的状态
        const cleanedState = {
          deviceId: parsed.state.deviceId,
          deviceName: parsed.state.deviceName,
          deviceType: parsed.state.deviceType,
          capabilities: parsed.state.capabilities,
          pairedDevices: parsed.state.pairedDevices || [],
          currentSession: parsed.state.currentSession
        }
        
        const cleanedData = {
          ...parsed,
          state: cleanedState
        }
        
        localStorage.setItem(deviceStorageKey, JSON.stringify(cleanedData))
        console.log('✅ 旧版本状态清理完成')
        return true
      }
    } catch (error) {
      console.error('❌ 清理存储状态时出错:', error)
      // 如果解析失败，清除整个数据
      localStorage.removeItem(deviceStorageKey)
      return true
    }
  }
  
  return false
} 